package br.com.bluetoothserver.util;

/**
 *  UNOPAR CCET - Promidia
 *  Copyright (C) 2011 Ben D'Orgio L. M. Pereira
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 *  @author Ben D'Orgio L. M. Pereira
 *  @version v1.0
 */

import java.util.ArrayList;
import java.util.List;

import br.com.bluetoothserver.dao.DAOMensagens;
import br.com.bluetoothserver.pojos.Mensagens;

/**
 * @class Handler
 * this class will handle the operation than make the choices
 * and return the correspondent arraylist
 */
public class Handler
{
	public List<Mensagens> getChoice(String message)
	{
		try
		{
			String[] result = message.split("#");
			
			switch(result.length)
			{
				case 1: // See all  messages
					return (new DAOMensagens()).getMessages(Integer.parseInt(result[0]));
				
				case 2: // See last messages
					return (new DAOMensagens()).getLastMessages(Integer.parseInt(result[0]),Integer.parseInt(result[1]));

				default:
					throw new Exception("unknown case");
			}
		}
		catch(Exception ex)
		{
			System.out.println("Handler exception: " + ex.getMessage() + " - " + ex.toString());
			ex.printStackTrace();
		}
		return new ArrayList<Mensagens>();
	}
	
	public String buildResponse(List<Mensagens> mensagens) throws Exception
	{
		if(mensagens.isEmpty()) {throw new Exception("index out of bounds : mensagens = 0");}
		
		final int size = mensagens.size()-1;
		String r = "";
		
		for(int i=0;i<size;i++)
		{
			r += mensagens.get(i).getId() 			+ "#";
			r += mensagens.get(i).getTitulo() 		+ "#";
			r += mensagens.get(i).getConteudo() 	+ "#";
			r += mensagens.get(i).getDataInicial() 	+ "#";
			r += mensagens.get(i).getDataFinal()   	+ "#";
		}
		
		r += mensagens.get(size).getId() 			+ "#";
		r += mensagens.get(size).getTitulo() 		+ "#";
		r += mensagens.get(size).getConteudo() 		+ "#";
		r += mensagens.get(size).getDataInicial() 	+ "#";
		r += mensagens.get(size).getDataFinal();
		
		return r;
	}
}
